<template>
  <BaseModal 
    v-model="visible" 
    title="登录"
    size="small"
    @close="handleClose"
  >
    <!-- Logo区域 -->
    <div class="logo-section">
      <div class="logo-circle">
        <div class="logo-inner">
          <el-icon size="28"><User /></el-icon>
        </div>
      </div>
      <h3 class="modal-subtitle">欢迎回来，请登录您的账户</h3>
    </div>
    
    <!-- 登录表单 -->
    <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" class="apple-form">
      <div class="form-group">
        <label class="form-label">用户名</label>
        <div class="input-wrapper">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名或手机号"
            size="large"
            class="apple-input"
            clearable
            @keyup.enter="submitForm"
          >
            <template #prefix>
              <el-icon class="input-icon"><User /></el-icon>
            </template>
          </el-input>
          <div class="input-tip">支持使用用户名或手机号登录</div>
        </div>
      </div>
      
      <div class="form-group">
        <label class="form-label">密码</label>
        <div class="input-wrapper">
          <el-input 
            type="password" 
            v-model="loginForm.password" 
            placeholder="请输入密码"
            size="large"
            class="apple-input"
            show-password
            clearable
            @keyup.enter="submitForm"
          >
            <template #prefix>
              <el-icon class="input-icon"><Lock /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
      
      <div class="form-actions">
        <el-button 
          type="primary" 
          @click="submitForm" 
          size="large" 
          class="apple-button"
          :loading="loading"
        >
          <span v-if="!loading">登录</span>
          <span v-else>登录中...</span>
        </el-button>
      </div>
    </el-form>
    
    <!-- 底部链接 -->
    <template #footer>
      <div class="auth-links">
        <el-button type="text" @click="goToRegister" class="apple-link">
          注册账号
        </el-button>
        <el-button type="text" @click="goToForgotPassword" class="apple-link">
          忘记密码
        </el-button>
      </div>
    </template>
  </BaseModal>
  
  <!-- 忘记密码模态框 -->
  <ForgotPasswordModal 
    v-model="showForgotPassword"
    @close="showForgotPassword = false"
    @switch-to-login="handleSwitchToLogin"
  />
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import { login as loginApi } from '../../api/auth';
import { useUserStore } from '../../stores/user';
import BaseModal from '../Modals/BaseModal.vue';
import ForgotPasswordModal from './ForgotPasswordModal.vue';

interface Props {
  modelValue: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  'close': [];
  'switch-to-register': [];
  'switch-to-forgot-password': [];
}>();

const router = useRouter();
const loginFormRef = ref<any>(null);
const userStore = useUserStore();
const loading = ref(false);
const showForgotPassword = ref(false);

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

const loginForm = reactive({
  username: '',
  password: '',
});

const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
  ],
});

const submitForm = () => {
  loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        const response = await loginApi({
          username: loginForm.username,
          password: loginForm.password,
        });

        ElMessage.success(response.data.message);
        // 存储 token 和用户信息
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('user', JSON.stringify(response.data.user));
        localStorage.setItem('userInfo', JSON.stringify(response.data.user));
        localStorage.setItem('loggedIn', 'true'); // 设置登录状态标识
        
        // 初始化用户store
        userStore.setToken(response.data.token);
        userStore.setUserInfo(response.data.user);
        
        // 关闭模态框
        handleClose();
        
        // 登录成功后刷新页面以更新状态
        window.location.reload();
      } catch (error: any) {
        console.error('登录请求失败:', error);
        if (error.response) {
          // 请求已发出，但服务器响应的状态码不在 2xx 范围内
          console.error('错误响应数据:', error.response.data);
          console.error('错误响应状态:', error.response.status);
          console.error('错误响应头:', error.response.headers);
          ElMessage.error(`登录失败：${error.response.data.message || '服务器错误'}`);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          console.error('错误请求:', error.request);
          ElMessage.error('登录请求失败：服务器无响应，请检查网络或后端服务！');
        } else {
          // 在设置请求时发生了其他错误
          console.error('错误信息:', error.message);
          ElMessage.error(`登录请求失败：${error.message}，请稍后再试！`);
        }
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.error('请填写完整信息！');
      return false;
    }
  });
};

const handleClose = () => {
  emit('update:modelValue', false);
  emit('close');
};

const goToRegister = () => {
  handleClose();
  emit('switch-to-register');
};

const goToForgotPassword = () => {
  handleClose();
  emit('switch-to-forgot-password');
};

const handleSwitchToLogin = () => {
  showForgotPassword.value = false;
};
</script>

<style scoped>
/* Logo区域 */
.logo-section {
  text-align: center;
  margin-bottom: 24px;
}

.logo-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.logo-circle:hover {
  transform: scale(1.05);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.logo-inner {
  width: 52px;
  height: 52px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #667eea;
}

.modal-subtitle {
  font-size: 16px;
  color: #86868b;
  margin: 0;
  font-weight: 400;
}

/* 表单样式 */
.apple-form {
  margin-bottom: 16px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 8px;
}

.input-wrapper {
  position: relative;
}

/* 苹果风格输入框 */
.apple-input {
  width: 100%;
}

:deep(.apple-input .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 12px 16px;
  transition: all 0.2s ease;
}

:deep(.apple-input .el-input__wrapper:hover) {
  border-color: rgba(102, 126, 234, 0.4);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

:deep(.apple-input.is-focus .el-input__wrapper) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.apple-input .el-input__inner) {
  font-size: 16px;
  color: #1d1d1f;
  font-weight: 400;
}

:deep(.apple-input .el-input__inner::placeholder) {
  color: #86868b;
}

.input-icon {
  color: #86868b;
  font-size: 18px;
}

.input-tip {
  font-size: 12px;
  color: #86868b;
  margin-top: 6px;
  text-align: left;
}

/* 表单操作区域 */
.form-actions {
  margin-top: 24px;
}

/* 苹果风格按钮 */
.apple-button {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-size: 16px;
  font-weight: 600;
  color: white;
  box-shadow: 0 4px 14px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

:deep(.apple-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

:deep(.apple-button:active) {
  transform: translateY(0);
  box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
}

/* 底部链接 */
.auth-links {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.apple-link {
  font-size: 14px;
  color: #667eea;
  font-weight: 500;
  padding: 0;
  transition: all 0.2s ease;
}

:deep(.apple-link:hover) {
  color: #5a6fd8;
  transform: translateY(-1px);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .logo-circle {
    width: 50px;
    height: 50px;
  }
  
  .logo-inner {
    width: 42px;
    height: 42px;
  }
  
  .modal-subtitle {
    font-size: 14px;
  }
  
  .auth-links {
    flex-direction: column;
    gap: 12px;
  }
}
</style>